// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {

        audioBg: {
            type: cc.AudioClip,
            default: []
        },

        pointNode:{
            type:cc.Node,
            default:null
        },

        fightSelectLabel:{
            type:cc.Node,
            default:null
        },
        
        fightSelectMask:{
            type:cc.Node,
            default:null
        },

        btnAttack:{
            type:cc.Node,
            default:null
        },

        btnSkill:{
            type:cc.Node,
            default:null
        },

        btnItem:{
            type:cc.Node,
            default:null
        },

        btnWait:{
            type:cc.Node,
            default:null
        },

        btnAuto:{
            type:cc.Node,
            default:null
        },

        btnLock:{
            type:cc.Node,
            default:null
        },

        btnSpeed:{
            type:cc.Node,
            default:null
        },

        btnCheck:{
            type:cc.Node,
            default:null
        },

        btnSwitch:{
            type:cc.Node,
            default:null
        },

        btnRun:{
            type:cc.Node,
            default:null
        },

        menuLabel:{
            type:cc.Node,
            default:null
        },

        gameMaskLabel:{
            type:cc.Node,
            default:null
        },

        skillaniLabel:{
            type:cc.Node,
            default:null
        },
    },

    // LIFE-CYCLE CALLBACKS:  

    // onLoad () {},

    start () {
        _Ep.setNode(this.node,0.8);
        _TIPS.setNode(this.node);
        _MGD.setParentNode(this.node);
        _CHESSBUTTON.setSence(this);
        _MJOB.setParentNode(this.node,false);
        window._CHESSFIGHT = this;
        this.autofight = window.gameData.autofight;
        this.startY = 6;
        this.startX = 4;
        this.playerNodeMap = {};//当前角色集合：角色坐标->角色信息+角色节点
        this.jumpMap = {};
        this.passMap = {};
        this.extraMap = {};
        this.hasPassPoint = false;
        this.currentPlayer = null;
        this.currentPlayerNode = null;
        this.currentRoleData = null;
        this.currentFanwei = null;
        this.currentAttackFanwei = null;
        this.currentKey = null;
        this.targetX=null;
        this.targetY=null;
        this.targetAction=null;
        this.movePath = null;
        this.moveIndex = 0;
        this.moveTime = 0.2;
        this.canClick = false;
        this.onlyMove = false;
        this.isCheck = false;
        this.currentCommond = null;
        this.currentSkill = null;
        this.currentItem = null;
        this.gameMaskLabel.active = true;
        this.defaultMap = null;
        this.playerStep=0;
        this.armyStep=0;

        this.actionArr = null;//行动队列
        this.actionIndex = null;//行动序号

        this.allPlayerCode = 0;
        this.allPlayerNodeMap = {};//所有角色集合：角色code->角色节点（node）+角色信息（info）

        this.tipsIndex = 0;
        this.aniIndex = 0;
        this.tipsArr = [];//提示信息数组

        this.initFightData();

        if(window.gameData.isPlayAudio){
            this.playBgm('fight',this.audioBg);
        }

        this.tiledMap = this.node.getChildByName('map').getComponent(cc.TiledMap);
		
		cc.loader.loadRes("map/"+this.defaultMap, function(err, map){

            _CHESSFIGHT.tiledMap.tmxAsset = map;

            _CHESSFIGHT.playerLabel = _CHESSFIGHT.tiledMap.node.getChildByName('playerLabel');

            _CHESSFIGHT.messageLabel = _CHESSFIGHT.tiledMap.node.getChildByName('messageLabel');

            _CHESSFIGHT.moveLabel = _CHESSFIGHT.tiledMap.node.getChildByName('moveLabel');

            _CHESSFIGHT.maxH = _CHESSFIGHT.tiledMap._mapSize.height;
            _CHESSFIGHT.maxW = _CHESSFIGHT.tiledMap._mapSize.width;

            _CHESSFIGHT.tiledMap.node.on(cc.Node.EventType.TOUCH_START, _CHESSFIGHT.mapClickFuc, _CHESSFIGHT.tiledMap.node); 
            _CHESSFIGHT.initFighter();
            _CHESSFIGHT.initJump();
            _CHESSFIGHT.initExtra();
            _CHESSFIGHT.initPass();
            _CHESSFIGHT.getNextPlayer();
            _CHESSBUTTON.initButton();
            _CHESSBUTTON.setFightSpeed(); 

            if(!window.gameData.showFightStory){
                window.gameData.showFightStory=1;
                var talkObj = _TALKHELPER.createFightStartTalk(); 
                _MANAGERTALK.showTalk(_CHESSFIGHT.node,talkObj,_CHESSFIGHT);
            }

            _CHESSFIGHT.gameMaskLabel.active = false;
		});

    },

    playBgm:function(bgmname,audioBgArr){
		
		for(var i=0;i<audioBgArr.length;i++){
			
			if(audioBgArr[i].name == bgmname){
				
				cc.audioEngine.play(audioBgArr[i], true, 1);
				
				break;
				
			}
			
		}
		
	},

    //根据角色code获取角色节点
    getPlayerNodeByCode:function(player){

        if(
            player
            &&player.code
            &&this.allPlayerNodeMap[player.code]
        ){
            return this.allPlayerNodeMap[player.code].node;
        }

        return null;

    },

    //根据角色code获取角色信息
    getPlayerInfoByCode:function(code){

        if(this.allPlayerNodeMap[code]){
            return this.allPlayerNodeMap[code].info;
        }

        return null;

    },

    //设置code和角色信息+角色节点的对应关系
    setPlayerNodeByCode:function(code,player,playerNode){
        this.allPlayerNodeMap[code]={info:player,node:playerNode};
    },

    //生成单位唯一编号
    getNextPlayerCode:function(){
        this.allPlayerCode++;
        return this.allPlayerCode;
    },

    //回收资源
    giveBackAll:function(){
        _GRM.getBackNode(this.playerLabel);
        //_GRM.getBackNode(this.node);
        _TIPS.giveBackTips();
    },

    //最终战BOSS
    jumpBossBack:function(){
        //_GRM.getBackNode(this.playerLabel);
        this.giveBackAll();
        window.gameData.targetPoint='1';//目标坐标点
        window.gameData.defaultMap='聚贤楼';//默认地图
        window._JUMPSENCE = 'map'
        cc.director.loadScene('jump');
    },

    //撤退
    jumpSuccess:function(){
        //_GRM.getBackNode(this.playerLabel);
        this.giveBackAll();
        window.gameData.targetPoint=null;//目标坐标点
        //window.gameData.defaultMap='大地图';//默认地图
        window._JUMPSENCE = 'map'
        cc.director.loadScene('jump');
    },

    jumpBack:function(){
        //_GRM.getBackNode(this.playerLabel);

        if(!_GAMEDATAHELPER.reduceItemByName('炉石')){
            this.giveBackAll();
            window.gameData.targetPoint="游戏开始";//目标坐标点
            //window.gameData.defaultMap='大地图';//默认地图
            window.gameData.defaultMap='如意画卷';//默认地图
            window._JUMPSENCE = 'map';
            cc.director.loadScene('jump');
        }else{
            this.jumpSuccess();
        }
    },

    //pk胜利
    jumpPkBack:function(){
        //_GRM.getBackNode(this.playerLabel);
        this.giveBackAll();
        window.gameData.targetPoint='默认';//目标坐标点
        window.gameData.defaultMap='西岐';//默认地图
        window._JUMPSENCE = 'map'
        cc.director.loadScene('jump');
    },


    //跳转下一层
    jumpToNextLevel:function(){
        //完成新手任务
        _TTCH.doCompleteTask('passChapter',window.fightData.chapter,false);
        //标记主线通关
        _MFR.updateChapterWork(window.fightData.chapter,window.fightData.level+1);
        
        if(!window.gameData.lockChapterLevel){
            window.fightData.level++;
        }
        //_GRM.getBackNode(this.playerLabel);
        this.giveBackAll();
        cc.director.loadScene('jump');

    },

    //跳转出口
    jumpToChapterOut:function(){
        //_GRM.getBackNode(this.playerLabel);
        this.giveBackAll();
        window.gameData.targetPoint=window.fightData.chapter+'后';//目标坐标点
        window.gameData.defaultMap='大地图';//默认地图
        window._JUMPSENCE = 'map'
        cc.director.loadScene('jump');

    },

    initFightData:function(){
        //清理阵亡角色
        if(window.fightData&&window.fightData.playerTeam&&window.fightData.playerTeam.length>0){
            console.log('清理阵亡角色');
            for(var i=0;i<window.fightData.playerTeam.length;){
                if(window.fightData.playerTeam[i].hp>0){
                    window.fightData.playerTeam[i].historyAnimals={};
                    window.fightData.playerTeam[i].animals=null;
                    i++;
                }else{
                    window.fightData.playerTeam.splice(i,1);
                }
            }
        }

        if(window.fightData.boss){
            _MCFC.initTaskData(null);
        }else if(_MTZ.isTzModel()){
            _MCFC.initTzData(window.fightData.tzChapter);
        }else{
            var areaname = window.fightData.areaType;
            _MCFC.initNormalData(areaname);
        }

        for(var i=0;i<window.fightData.armyTeam.length;i++){
            window.fightData.armyTeam[i].historyAnimals={};
            window.fightData.armyTeam[i].animals=null;
        }
        
        this.initTitle();
    },

    initPkData:function(){

        window.fightData.armyTeam=[];
        var randomBoss = window.fightData.boss;
        var bossConf = _NPC[randomBoss];
        if(bossConf){
            var bossLevel = bossConf.level;
            var chapterLv = bossLevel*100;
            var bossdzlevel = bossLevel*100;
            var bosslv = bossLevel*100;
            if(bosslv>1000){
                bosslv=1000;
            }
            this.defaultMap = '擂台';
            window.fightData.armyTeam.push(
                _CROF.createNpcRole(randomBoss,
                    {dzlevel:bossdzlevel,lv:bosslv,chapterLv:chapterLv,chapter:this.getBossChapter(randomBoss)}
                )
            );
        }  
    },

    getBossChapter:function(bossname){

        for(var key in _CMAP){

            for(var i=0;i<_CMAP[key].boss.length;i++){
                if(_CMAP[key].boss[i]==bossname){
                    return key;
                }
            }

        }

        return null;
    },

    //最终战斗
    initFinalBossFight:function(){

        var mapconf = _FBOSS[window.fightData.chapter];
        var bigBoss = mapconf.bigBoss;
        var bossArr = mapconf.boss;
        var armyLv = mapconf.level;
        var armyNmb = mapconf.baseNmb;//基础人数
        var dzlevel = mapconf.elevel;
        var chapterLv = mapconf.chapterLv;
        var chapter = mapconf.chapter;
        this.defaultMap = mapconf.map;
        window.fightData.armyTeam=[];

        window.fightData.armyTeam.push(
            _CROF.createNpcRole(bigBoss,
                {dzlevel:dzlevel,lv:armyLv,chapterLv:chapterLv,chapter:chapter}
            )
        );

        for(var i=0;i<armyNmb;i++){
            var randomBoss = _CU.randomObj(bossArr);
            window.fightData.armyTeam.push(
            _CROF.createNpcRole(randomBoss,
                {dzlevel:dzlevel,lv:armyLv,chapterLv:chapterLv,chapter:chapter}
            ));
        }
    },

    cancelCommond:function(){
        this.currentCommond=null;
        this.fightSelectLabel.active = false;
        this.pointNode.active = false;
        this.hidefanwei();
        this.showfanweibyMap(_CHESSFIGHT.currentFanwei);
    },

    //判断战斗是否结束
    isfightOver:function(){

        if(this.currentPlayer.isplayer){
            this.playerStep++;
        }else{
            this.armyStep++;
        }
        this.refreshStepNmb();

        var playerNmb = 0;
        var armyNmb = 0;
        var ispass = false;
        var ispassChapter = false;

        for(var key in this.playerNodeMap){
            if(
                this.playerNodeMap[key]
                &&this.playerNodeMap[key].info
                &&this.playerNodeMap[key].node
            ){
                if(this.playerNodeMap[key].info.hp>0){
                    if(this.playerNodeMap[key].info.isplayer){
                        playerNmb++;
                        if(this.jumpMap[key]){
                            ispass = true;
                        }
                        if(this.passMap[key]){
                            ispassChapter = true;
                        }
                    }else{
                        armyNmb++;
                    }
                }
            }
        }

        if(armyNmb<=0){

            if(window.fightData.isFightBoss){

                var pkreward = window.fightData.boss+"碎片";
                var dropSkill = _SKILLHEPLER.getSkillOfDrop(window.fightData.boss);
                var message = "挑战成功";
                if(dropSkill&&dropSkill.length>0){
                    var randomSkill = _CU.randomObj(dropSkill);
                    _GAMEDATAHELPER.pushItem(_IOF.createObjByName(randomSkill));
                    message+=",获得"+randomSkill+"*1"
                }

                if(_FIGHTITEM[pkreward]){
                    _GAMEDATAHELPER.pushItem(_IOF.createObjByName(pkreward));
                    message+=",获得"+pkreward+"*1"
                }

                _TIPS.showMessage(message);

                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((3)),
                        cc.callFunc(function(){
                            this.jumpPkBack();
                        },this)
                    )
                );

                

            }else if(window.fightData.isFinal){

                _TIPS.showMessage("恭喜通关！（存档后重新开始游戏可以选择存档继承）");

                //标记通关
                window.gameData.fsbpass = true;

                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((3)),
                        cc.callFunc(function(){
                            this.jumpBossBack();
                        },this)
                    )
                );

            }else{

                /*
                if(!window.gameData.lockChapterLevel)
                    _TIPS.showMessage("我军获胜,正在进入下一层");
                else
                    _TIPS.showMessage("我军获胜,正在重新进入本层(解除锁定可进入下一层)");
                */
               if(_MTZ.isTzModel()){
                    var tzConf = _CTZ[window.fightData.tzChapter];
                    var reward = tzConf.reward;
                    _GAMEDATAHELPER.setTzLog(window.fightData.tzChapter);
                    //_GAMEDATAHELPER.setTzTeam(window.fightData.tzChapter,window.fightData.playerTeam);
                    _GAMEDATAHELPER.pushItem(_IOF.createObjByName(reward));
                    _TIPS.showMessage("我军获胜,获得:"+reward);
               }else{
                    if(!this.isTaskModel()){
                        _TIPS.showMessage("我军获胜,正在返回大地图");
                    }else{
                        _MXYT.completeTask();
                        _TIPS.showMessage("主线任务完成,正在返回大地图");
                    }
               }

                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((2)),
                        cc.callFunc(function(){
                            //this.jumpToNextLevel();
                            this.jumpSuccess();
                        },this)
                    )
                );

            }

            /*
            if(!this.hasPassPoint){
                //_CHOICEMANAGER.showChoice(this.node,'successChessFight',{nocancel:true});
                _TIPS.showMessage("我军获胜,正在进入下一层");

                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((2)),
                        cc.callFunc(function(){
                            this.jumpToNextLevel();
                        },this)
                    )
                );

            }else{
                _CHOICEMANAGER.showChoice(this.node,'successAndPassChessFight',null);
            }
            return true;
            */
            return true;
        }

        if(ispass){
            this.jumpToNextLevel();
            return true;
        }

        if(ispassChapter){
            this.jumpToChapterOut();
            return true;
        }

        if(playerNmb<=0){
            //_TIPS.showMessage('战斗失败！');
            if(window.fightData.isFightBoss){
                _TIPS.showMessage("挑战失败");
                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((2)),
                        cc.callFunc(function(){
                            this.jumpPkBack();
                        },this)
                    )
                );
            }else if(window.fightData.isFinal){
                _TIPS.showMessage("挑战失败");
                this.node.runAction(
                    cc.sequence(
                        cc.delayTime((2)),
                        cc.callFunc(function(){
                            this.jumpBossBack();
                        },this)
                    )
                );
            }else{
                _CHOICEMANAGER.showChoice(this.node,'faileChessFight',{nocancel:true});
            }
            return true;
        }

        //主线任务行动次数超过上限
        if(this.isTaskModel()
            &&this.playerStep>_CS.stepMax
        ){
            _CHOICEMANAGER.showChoice(this.node,'stepChessFight',{nocancel:true});
            return true;
        }

        this.createExtraByTime();
        this.getNextPlayer();
        return false;
    },

    //刷新战斗单位坐标
    refreshPlayerNodeMap:function(){

        //清理已经阵亡的角色
        var newarr = [];
        for(var key in this.playerNodeMap){
            if(
                this.playerNodeMap[key]
                &&this.playerNodeMap[key].info
                &&this.playerNodeMap[key].node
            ){
                if(this.playerNodeMap[key].info.hp>0){
                    newarr.push(this.playerNodeMap[key]);
                }else{
                    _GRM.putNode(this.playerNodeMap[key].node);
                }
            }
        }

        //刷新所有存活角色坐标
        this.playerNodeMap = {};
        for(var i=0;i<newarr.length;i++){
            var playerNode = newarr[i].node;
            var playerInfo = newarr[i].info;
            var playerPos = this.getPlayerPos(playerInfo);
            var npcmappos = _MANAGERMAP.getMapNodePosByTiled(playerPos.x,playerPos.y,this.maxH,this.maxW);
            playerNode.stopAllActions();
            playerNode.setPosition(cc.v2(npcmappos));
            //playerNode.getChildByName('role').getComponent(cc.Animation).play('aida2');
            playerNode.getChildByName('role').color = new cc.color("#FFFFFF");
            _MFN.refreshPlayerNode(playerNode,playerInfo);
            this.playerNodeMap[playerPos.x+"-"+playerPos.y]=newarr[i];
        }
    },

    hideController:function(){
        this.canClick = false;
        this.fightSelectLabel.active = false;
        _CHESSFIGHT.pointNode.active = false;
        _CHESSFIGHT.hidefanwei();
    },

    waitAction:function(){
        this.hideController();
        var movePath = _MCFW.getMovePath(this.currentPlayer,this.targetX,this.targetY,this.currentFanwei);
        this.targetAction = {type:_MCF._ATYPE_WAIT,path:movePath};            
        this.doAction();
    },

    setPlayerPos:function(player,x,y){
        if(player){
            player.chessPos = {x:x,y:y};
        }
    },

    getPlayerPos:function(player){
        if(player){
            return player.chessPos;
        }

        return null;
    },

    isTargetInCurrentFanwei:function(target){
        var playerPos = this.getPlayerPos(target);
        if(playerPos){
            return this.currentFanwei[playerPos.x+"-"+playerPos.y];
        }
    },

    //判定单次移动是否能进入该点
    isTargetInCurrentFanweiMove:function(x,y){
        return this.currentFanwei[x+"-"+y]
                &&!this.currentFanwei[x+"-"+y].isattack
                &&!this.currentFanwei[x+"-"+y].ispass
                &&!this.playerNodeMap[x+"-"+y];
    },

    //获取技能作用单位
    getItemTargetArr:function(targetpos,item){

        var targetArr = [];
        var itemConf = _FIGHTITEM[item];
        var roleScope = _CHESSFIGHT.currentRoleData?_CHESSFIGHT.currentRoleData.aqScope:0;
        var itemScope = itemConf.scope;
        var skillfanwei = _MCFW.getfanweiMap(
            {
                x:targetpos.x,
                y:targetpos.y,
                len:0,
                attacklen:itemScope+roleScope,
                tiledMap:this.tiledMap,
                maxH:this.maxH,
                maxW:this.maxW,
                playerNodeMap:this.playerNodeMap,
                player:this.currentPlayer
            }
        );
        //console.log('技能范围:',skillfanwei);
        for(var key in skillfanwei){

            if(
                _CHESSFIGHT.playerNodeMap[key]
                &&(
                    (
                    _CHESSFIGHT.playerNodeMap[key].info.isplayer==_CHESSFIGHT.currentPlayer.isplayer
                    &&itemConf.target=="friend"
                    )||(
                    _CHESSFIGHT.playerNodeMap[key].info.isplayer!=_CHESSFIGHT.currentPlayer.isplayer
                    &&itemConf.target=="army"
                    )

                )
            ){
                targetArr.push( _CHESSFIGHT.playerNodeMap[key]);
            }

        }
        //console.log('技能目标:',targetArr);
        this.showfanweibyMap(skillfanwei);
        return targetArr;
    },


    getSkillTargetArr:function(targetpos,currentSkill){

        var targetArr = [];
        var playerData = _ROLEDATA.getRoleDataOfPlayer(this.currentPlayer);
        var skillScope = _SKILL[currentSkill].distance;
        var skillAttackLen = skillScope?(skillScope+playerData.scope-1):0;//技能范围+整幅-1(只针对配置了distance的技能)
        var skillfanwei = _MCFW.getfanweiMap(
            {
                x:targetpos.x,
                y:targetpos.y,
                len:0,
                attacklen:skillAttackLen,
                tiledMap:this.tiledMap,
                maxH:this.maxH,
                maxW:this.maxW,
                playerNodeMap:this.playerNodeMap,
                player:this.currentPlayer
            }
        );
        //console.log('技能范围:',skillfanwei);
        for(var key in skillfanwei){

            if(
                _CHESSFIGHT.playerNodeMap[key]
                &&(
                    (
                    _CHESSFIGHT.playerNodeMap[key].info.isplayer==_CHESSFIGHT.currentPlayer.isplayer
                    &&_SKILL[currentSkill].target=="friend"
                    )||(
                    _CHESSFIGHT.playerNodeMap[key].info.isplayer!=_CHESSFIGHT.currentPlayer.isplayer
                    &&_SKILL[currentSkill].target=="army"
                    )

                )
            ){
                targetArr.push( _CHESSFIGHT.playerNodeMap[key]);
            }

        }

        //以自身为目标的buff技能,如果目标不存在则选中自身（针对移动后失去目标）
        if(
            !_SKILL[currentSkill].single
            &&_SKILL[currentSkill].target=="friend"
            &&targetArr.length<=0
        ){
            if(
                this.currentPlayer
                &&this.currentPlayer.chessPos
            ){
                var currentKey = this.currentPlayer.chessPos.x+"-"+this.currentPlayer.chessPos.y;
                if(this.playerNodeMap[currentKey]){
                    targetArr.push(this.playerNodeMap[currentKey]);
                }
            }
            
        }

        //console.log('技能目标:',targetArr);
        this.showfanweibyMap(skillfanwei);
        return targetArr;
    },

    //角色回合开始前结算
    beforeAction:function(){

        this.tipsArr.length = 0;

        _CHESSFIGHT.currentPlayer.eg-=100;

        //回合开始结算状态
        if(_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.currentPlayer,'du')){
            var dublood = Math.floor(_CHESSFIGHT.currentPlayer.hp*_CS.duper);
            if(dublood>_CS.dumax){
                dublood=_CS.dumax;
            }
            dublood=_MFD.cutHp(_CHESSFIGHT.currentPlayer,dublood,null);
            this.tipsArr.push({msg:"中毒-"+_CU.getUnitNmb(dublood),color:_CS.duColor});
        }

        var playerData = _ROLEDATA.getRoleDataOfPlayer(_CHESSFIGHT.currentPlayer);

        if(playerData.hpRecovery){

            var hp = Math.floor(playerData.maxHp*(playerData.hpRecovery/100));
            var realhp  = _MFD.addHp(_CHESSFIGHT.currentPlayer,hp);
            this.tipsArr.push({msg:"回血"+_CU.getUnitNmb(realhp),color:_CS.hpcolor});
        }

        if(playerData.MagicRecovery){

            var magic = playerData.MagicRecovery;
            var realmagic  = _MFD.addMagic(_CHESSFIGHT.currentPlayer,magic);
            this.tipsArr.push({msg:"回蓝"+_CU.getUnitNmb(realmagic),color:_CS.langcolor});
        }

        //未来战士行动前召唤科技单位
        if(playerData.invent){
            _MCAC.doKejiFenshen(_CHESSFIGHT.currentPlayer,_CHESSFIGHT);
            this.tipsArr.push({msg:"发明",color:_CS.skillcolor});
        }

        if(this.tipsArr.length>0){
            this.showTips(this.tipsArr,_CHESSFIGHT.currentPlayerNode);
        }

        _STATUSHELPERCHESS.reduceStatus(_CHESSFIGHT.currentPlayer);

        _MFN.refreshPlayerNode(_CHESSFIGHT.getPlayerNodeByCode(_CHESSFIGHT.currentPlayer),_CHESSFIGHT.currentPlayer);

    },

    turnToPlayer:function(){

        if(_CHESSFIGHT.currentPlayerNode){
            _CHESSFIGHT.currentPlayerNode.getChildByName('selected').active = false;
        }
        _CHESSFIGHT.currentCommond=null;
        _CHESSFIGHT.pointNode.active = false;
        _CHESSFIGHT.hidefanwei();
        _CHESSFIGHT.currentPlayer = _CHESSFIGHT.playerNodeMap[this.currentKey].info;
        _CHESSFIGHT.currentPlayerNode = _CHESSFIGHT.playerNodeMap[this.currentKey].node;
        _CHESSFIGHT.currentRoleData = _ROLEDATA.getRoleDataOfPlayer(_CHESSFIGHT.currentPlayer);
        _CHESSFIGHT.currentPlayerNode.getChildByName('selected').active = true;

        _CHESSFIGHT.beforeAction();

        var mapPos = _CHESSFIGHT.getPlayerPos(_CHESSFIGHT.currentPlayer);
        _CHESSFIGHT.currentFanwei =_MCFW.getfanweiMap(
                                        //mapPos.x,mapPos.y,_CHESSFIGHT.currentRoleData.move,_CHESSFIGHT.currentRoleData.distance

                                        {
                                            x:mapPos.x,y:mapPos.y,
                                            len:_CHESSFIGHT.currentRoleData.move,
                                            attacklen:_CHESSFIGHT.currentRoleData.distance,
                                            tiledMap:_CHESSFIGHT.tiledMap,
                                            maxH:_CHESSFIGHT.maxH,
                                            maxW:_CHESSFIGHT.maxW,
                                            playerNodeMap:_CHESSFIGHT.playerNodeMap,
                                            player:_CHESSFIGHT.currentPlayer
                                        }

                                    );
        _CHESSFIGHT.showfanweibyMap(_CHESSFIGHT.currentFanwei);

        if(_STATUSHELPERCHESS.canPlayerDoAction(_CHESSFIGHT.currentPlayer)){
            //非自动 且没有中混乱和嘲讽的玩家角色 则为手动模式
            if(_CHESSFIGHT.currentPlayer.isplayer
                &&!_CHESSFIGHT.autofight
                &&!_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.currentPlayer,'nu')
                &&!_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.currentPlayer,'luan')
            ){
                this.canClick = true;
                this.onlyMove = false;
            }else{
                this.node.runAction(
                    cc.sequence(
                        cc.delayTime(this.moveTime),
                        cc.callFunc(function(){
                            _MCA.aiAction();
                        },this)
                    )
                );
            }
        }else{
            _MCA.waitBack();
        }
    },

    getNextPlayer:function(){

        var maxeg = 0;
        var hasPlayer = false;

        for(var key in this.playerNodeMap){
            var tmpeg = this.playerNodeMap[key].info.eg;
            
            if(tmpeg>maxeg){
                maxeg = tmpeg;
                this.currentKey = key;
            }

            hasPlayer = true;
        }

        if(!hasPlayer){
            this.jumpBack();
            return;
        }

        if(maxeg<100){

            for(var key in this.playerNodeMap){
            
                var tmproledata = _ROLEDATA.getRoleDataOfPlayer(this.playerNodeMap[key].info);
                this.playerNodeMap[key].info.eg+=tmproledata.speed;
    
            }

            this.getNextPlayer();

        }else{
            this.refreshPlayerNodeMap();
            this.refreshTitle();
            this.turnToPlayer();
        }
    },

    //计算承伤
    protectPlayer:function(target,damage){

        var tanke = null;
        var tankeNode = null;

        if(
            target
            &&target.chessStatus
            &&target.chessStatus.status=="hu"
        ){//先判断‘护’

            var sourceCode = target.chessStatus.sourceCode;
            tanke = this.getPlayerInfoByCode(sourceCode);
            tankeNode = this.getPlayerNodeByCode(tanke);

        }else{//再判断‘替’

            for(var key in this.allPlayerNodeMap){

                var tmpplayer = this.allPlayerNodeMap[key].info;
                var tmpplayerNode = this.allPlayerNodeMap[key].node;
                if(
                    tmpplayer
                    &&tmpplayer.chessStatus
                    &&tmpplayer.chessStatus.status=="ti"
                    &&tmpplayer.chessStatus.sourceCode==target.code
                    &&tmpplayer.code!=target.code
                ){
                    tanke = tmpplayer;
                    tankeNode=tmpplayerNode;
                    break;
                }

            }

        }

        if(
            tanke
            &&tankeNode
            &&tanke.code!=target.code
            &&tanke.hp>0
        ){
            var beforehp = tanke.hp;

            //保护伤害减半
            damage = Math.floor(damage/2);
            
            _MFD.cutHp(tanke,damage,null);
            var resultHp = 0;
            if(tanke.hp>0){
                resultHp = 0;
            }else{
                resultHp = damage-beforehp;
            }
            _MFN.refreshPlayerNode(tankeNode,tanke);
            this.showDamage("承伤"+_CU.getUnitNmb(beforehp-tanke.hp),null,tankeNode);
            return resultHp;
        }

        return damage;
    },

    //被打  isNormal 是否普攻  isAnqi是否真伤
    behit:function(player,target,targetNode,result,ani,isNormal,isAnqi){

        //攻击后解除隐身状态
        _STATUSHELPERCHESS.checkAndReduceStatus(player,"yin");

        var playerData = _ROLEDATA.getRoleDataOfPlayer(player);

        var targetData = _ROLEDATA.getRoleDataOfPlayer(target);

        var playerNode = this.getPlayerNodeByCode(player);

        var playerTips = [];
        var targetTips = [];

        if(!result.isMiss){

            //先计算承伤
            var realdamage = this.protectPlayer(target,result.damage);

            realdamage = _MFD.cutHp(target,realdamage,playerData);

            //var realdamage = _MFD.cutHp(target,result.damage);

            //console.log('伤害：',realdamage);

            if(!result.isSuper){
                //this.showDamage(realdamage,null,targetNode);
                targetTips.push({msg:_CU.getUnitNmb(realdamage),color:null});
            }else{
                //this.showDamage(realdamage,_CS.bjcolor,targetNode);
                targetTips.push({msg:_CU.getUnitNmb(realdamage),color:_CS.bjcolor});
            }

            //播放动画
            this.playSkillOnPlayer(ani,target);

            //计算击晕
            if(
                isNormal&&
                playerData.stun>0&&
                target.hp>0
            ){
                var baseStun = playerData.stun-targetData.stunMiss;
                var stunper = baseStun>90?90:baseStun;
                if(Math.random()<(stunper/100)){
                    _STATUSHELPERCHESS.addStatus(target,'yun',player);
                    playerTips.push({msg:"击晕",color:_CS.skillcolor});
                }
            }

            //计算淬毒
            if(
                isNormal
                &&playerData.poison>0
                &&target.hp>0
                &&Math.random()<(playerData.poison/100)){
                _STATUSHELPERCHESS.addStatus(target,'du',player);
                playerTips.push({msg:"淬毒",color:_CS.skillcolor});
            }

            //计算集气
            if(targetData.hitEnergy){
                target.eg+=targetData.hitEnergy;
                _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(target),target);
                targetTips.push({msg:"集气",color:_CS.skillcolor});
            }

            _MFN.refreshPlayerInfo(targetNode,target);
            //_MFN.refreshPlayerNode(targetNode,target);

            

            //计算吸血
            if(
                realdamage<0
                //&&isNormal
                &&!isAnqi
                &&player.hp>0
            ){
                var bloodPer = playerData.blood;
                if(bloodPer>0){
                    var blood = -Math.floor(realdamage*(bloodPer/100));
                    _MFD.addHp(player,blood);
                    _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(player),player);
                    playerTips.push({msg:"吸血"+_CU.getUnitNmb(blood),color:_CS.skillcolor});
                }
            }

            
            if(
                !isAnqi&&
                realdamage<0
                &&player.hp>0
            ){
                //计算反伤
                var fanshangPer = result.isMagic?targetData.mattackBack:targetData.attackBack;
                if(fanshangPer>0&&!playerData.ironwall){
                    var fanshang = -Math.floor(realdamage*(fanshangPer/100));
                    _MFD.cutHp(player,fanshang,null);
                    _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(player),player);
                    targetTips.push({msg:"反伤",color:_CS.skillcolor});
                    if(player.hp<=0){
                        _MCRD.setReward(target,{type:'kill',target:player,player:target});
                    }
                }
                //计算诅咒之躯
                if(targetData.statusBody){
                    var randomStatus = _CU.randomObj(window._DEBUFFARR);
                    _STATUSHELPERCHESS.addStatus(player,randomStatus,target);
                    _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(player),player);
                    targetTips.push({msg:"诅咒",color:_CS.skillcolor});
                }
            }


            //this.playBgm('blood',this.audioBg);
            if(target.hp<=0){
                //this.playBgm('die',this.audioBg);
                _MCRD.setReward(player,{type:'kill',target:target,player:player});
                targetNode.getChildByName('role').getComponent(cc.Animation).play('weak');
            }else{
                targetNode.getChildByName('role').getComponent(cc.Animation).play('aida');
                //console.log('挨打判断圣盾',realdamage,targetData.shendun);
                if(realdamage!=0&&targetData.shendun){
                    _STATUSHELPERCHESS.addStatus(target,'dun',target);
                    _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(target),target);
                    targetTips.push({msg:"圣盾",color:_CS.skillcolor});
                }
            }

        }else{

            //this.showDamage('miss',null,targetNode);
            targetTips.push({msg:"miss",color:null});
            if(targetData.missEnergy>0){
                target.eg+=targetData.missEnergy;
                _MFN.refreshPlayerInfo(this.getPlayerNodeByCode(target),target);
                targetTips.push({msg:"蓄势",color:_CS.skillcolor});
            }

        }

        if(targetTips.length>0){
            this.showTips(targetTips,targetNode);
        }

        if(playerTips.length>0){
            this.showTips(playerTips,playerNode);
        }

    },

    //##########角色行动流程
    //普通攻击
    attackAction:function(target){
        this.hideController();        
        var movePath = _MCFW.getMovePath(this.currentPlayer,this.targetX,this.targetY,this.currentFanwei);
        this.targetAction = {type:_MCF._ATYPE_ATTACK,path:movePath,target:target};            
        this.doAction();
    },


    //定向普通攻击
    attackTargetAction:function(target){
        var touchpos = this.isTargetInCurrentFanwei(target);
        if(touchpos){

            //console.log('攻击目标:',target);

            
            var movePath = _MCFW.getAttackPath(this.currentPlayer,touchpos,this.currentFanwei);

            //console.log('攻击路径:',movePath);

            if(movePath){
                this.hideController(); 
                this.targetAction = {
                                    type:_MCF._ATYPE_ATTACK,path:movePath,
                                    target:{info:target,node:this.getPlayerNodeByCode(target)}
                                    };            
                this.doAction();
                return true;
            }else{
                //_TIPS.showMessage("找不到进攻路线");
            }
        }

        return false;
    },

    //普通技能
    skillAction:function(target,currentSkill,param){

        this.currentSkill = currentSkill;

        this.hideController();

        var targetpos = target?this.getPlayerPos(target.info):null;
        var targetArr = targetpos?this.getSkillTargetArr(targetpos,currentSkill):null;
        var movePath = _MCFW.getMovePath(this.currentPlayer,this.targetX,this.targetY,this.currentFanwei);
        this.targetAction = {type:_MCF._ATYPE_SKILL,path:movePath,
                             targetArr:targetArr,target:targetpos,
                             skillParam:param};            
        this.doAction();

    },

    //道具
    itemAction:function(target,item,param){

        this.currentItem = item;

        this.hideController();

        var targetpos = target?this.getPlayerPos(target.info):null;
        var targetArr = targetpos?this.getItemTargetArr(targetpos,item):null;
        var movePath = _MCFW.getMovePath(this.currentPlayer,this.targetX,this.targetY,this.currentFanwei);
        this.targetAction = {type:_MCF._ATYPE_ITEM,path:movePath,
                             targetArr:targetArr,target:targetpos,
                             itemParam:param};            
        this.doAction();

    },

    //定向技能
    skillTargetAction:function(target,currentSkill){
        var touchpos = this.isTargetInCurrentFanwei(target);
        if(touchpos){
            var movePath = _MCFW.getAttackPath(this.currentPlayer,touchpos,this.currentFanwei);
            if(movePath){
                this.hideController();
                this.currentSkill = currentSkill;
                this.targetAction = {
                                    type:_MCF._ATYPE_SKILL,path:movePath,
                                    targetArr:this.getSkillTargetArr(this.getPlayerPos(target),this.currentSkill),
                                    target:this.getPlayerPos(target)};      
                this.doAction();
                return true;
            }else{
                //_TIPS.showMessage("找不到进攻路线:"+currentSkill);
                console.log("找不到进攻路线:"+currentSkill);
            }
        }

        return false;
    },

    //范围技能
    skillActionByPos:function(x,y,currentSkill){

        this.currentSkill = currentSkill;

        this.hideController();

        var targetpos = {x:x,y:y};
        var targetArr = this.getSkillTargetArr(targetpos,currentSkill);
        var movePath = _MCFW.getMovePath(this.currentPlayer,this.targetX,this.targetY,this.currentFanwei);
        this.targetAction = {type:_MCF._ATYPE_SKILL,path:movePath,targetArr:targetArr,target:targetpos};            
        this.doAction();

    },


    //自身传送类技能
    moveSkillAction:function(target,movetarget,currentSkill){

        this.currentSkill = currentSkill;
        var movePath = null;
        if(movetarget!=null){
            movePath = _MCFW.getMovePath(this.currentPlayer,movetarget.x,movetarget.y,this.currentFanwei);
        }
        this.targetAction = {type:_MCF._ATYPE_SKILL,path:movePath,
            targetArr:null,target:movetarget,
            skillParam:target};            
        this.doAction();

    },

    //传送单位技能
    moveRoleSkillAction:function(target,currentSkill){

        var enablePos = _MCFW.getPosForJump(this.currentPlayer);
        if(!enablePos||enablePos.length<=0){
            return false;
        }else{
            this.currentSkill = currentSkill;
            this.targetAction = {type:_MCF._ATYPE_SKILL,path:null,
                targetArr:null,target:null,
                skillParam:{
                    targetPlayer:target,
                    enablePosArr:enablePos
                }};

            this.doAction();
            return true;
        }
    },

    //传送攻击单位
    moveAttackSkillAction:function(target,currentSkill){

        var enablePos = _MCFW.getPosForJump(target.info);

        if(!enablePos||enablePos.length<=0){

            return false;

        }else{
            this.currentSkill = currentSkill;
            this.targetAction = {type:_MCF._ATYPE_SKILL,path:null,
                targetArr:null,target:null,
                skillParam:{
                    targetPlayer:target,
                    enablePosArr:enablePos
                }};            
            this.doAction();
            return true;
        }
    },

    //开始行动
    doAction:function(){

        if(this.targetAction){
            //this.currentPlayer.eg-=100;
            this.moveIndex=0;
            this.movePath = this.targetAction.path;
            this.playerMove();
        }

    },

    //第一步：移动
    playerMove:function(){

        //console.log('移动',this.moveIndex);

        if(!this.movePath||this.moveIndex>=this.movePath.length){

            if(this.targetAction.type==_MCF._ATYPE_WAIT){

                //this.doActionEnd();

                this.refreshPlayerNodeMap();
                this.isfightOver();

            }else if(this.targetAction.type==_MCF._ATYPE_ATTACK){

                this.createAttackActionArr(this.currentPlayer,this.targetAction.target.info);
                this.playerDoAction();

            }else if(this.targetAction.type==_MCF._ATYPE_SKILL){
                
                this.createSkillActionArr(this.currentPlayer,this.targetAction.target,
                                        this.targetAction.targetArr,this.currentSkill,
                                        this.targetAction.skillParam);
                this.playerDoAction();
            }else if(this.targetAction.type==_MCF._ATYPE_ITEM){

                this.createItemActionArr(this.currentPlayer,this.targetAction.target,
                    this.targetAction.targetArr,this.currentItem,
                    this.targetAction.itemParam);

                this.playerDoAction();
            }

        }else{

            //this.playBgm('horse',this.audioBg)

            var targetMovePos = this.movePath[this.moveIndex];
            this.setPlayerPos(this.currentPlayer,targetMovePos[0],targetMovePos[1]);
            var targetPosition  = _MANAGERMAP.getMapNodePosByTiled(targetMovePos[0],targetMovePos[1],this.maxH,this.maxW);
            this.switchPlayerDir(this.currentPlayerNode,targetMovePos);

            this.node.runAction(
                cc.sequence(
                    //cc.moveTo(this.moveTime,targetPosition),
                    cc.callFunc(function(){
                        this.currentPlayerNode.runAction(cc.moveTo(this.moveTime,targetPosition));
                    },this),
                    cc.delayTime(this.moveTime),
                    cc.callFunc(function(){
                        this.moveIndex++;
                        this.playerMove();
                    },this)
                )
            );


        }

    },

    //创建普通攻击执行队列
    createAttackActionArr:function(player,target){

        this.actionIndex = 0;
        this.actionArr = [];
        
        var isfanji = _ROLEDATA.getRealAttr(target,"fanji");
        var distance = _ROLEDATA.getRealAttr(target,"distance");

        this.createOnceAttackActionArr(player,target,isfanji,distance,'attack');

        var xiezhanplayers = this.getXiezhanArr(player,target);

        for(var i=0;i<xiezhanplayers.length;i++){

            this.createOnceAttackActionArr(xiezhanplayers[i],target,isfanji,distance,'attack1');

        }
                
    },

    //创建单次攻击队列
    createOnceAttackActionArr:function(player,target,isfanji,distance,attackType){

        var lianjinmb = _ROLEDATA.getRealAttr(player,"lianji");

        this.actionArr.push({player:player,target:target,type:attackType});

        for(var i=1;i<=lianjinmb;i++){
            this.actionArr.push({player:player,target:target,type:'attack2'});
        }
        if(
            isfanji>0
            &&_CU.getPlayerDis(player,target)<=distance
        ){
            this.actionArr.push({player:target,target:player,type:'attack3'});
        }

    },

    //创建技能队列
    createSkillActionArr:function(player,target,targetArr,skill,skillParam){

        this.actionIndex = 0;
        this.actionArr = [];
        var lianjiSkill = _ROLEDATA.getRealAttr(player,"lianjiSkill");
        var skillnmb = lianjiSkill>0?2:1;
        for(var i=0;i<skillnmb;i++){
            this.actionArr.push({player:player,target:target,targetArr:targetArr,skill:skill,type:'skill',skillParam:skillParam});
        }

    },

    //创建道具队列
    createItemActionArr:function(player,target,targetArr,item,itemParam){

        this.actionIndex = 0;
        this.actionArr = [];
        this.actionArr.push({
                            player:player,target:target,targetArr:targetArr,item:item,
                            type:'item',itemParam:itemParam}
                            );

    },

    //执行队列
    playerDoAction:function(){

        if(this.actionIndex<this.actionArr.length){
            var actionObj = this.actionArr[this.actionIndex];
            if(
                actionObj.type=="attack"
                ||actionObj.type=="attack1"//协战
                ||actionObj.type=="attack2"//连击
                ||actionObj.type=="attack3"//反击
            ){

                var target = actionObj.target;
                var player = actionObj.player;
                if(
                    target.hp>0
                    &&player.hp>0
                    &&_STATUSHELPERCHESS.canPlayerDoAction(player)
                ){
                    var targetNode = this.getPlayerNodeByCode(target);
                    var playerNode = this.getPlayerNodeByCode(player);
                    var targetPos = this.getPlayerPos(target);

                    this.switchPlayerDirAndActtack(playerNode,targetPos);

                    if(actionObj.type=="attack1"){
                        this.showAttackName('协战',playerNode);
                    }else if(actionObj.type=="attack2"){
                        this.showAttackName('连击',playerNode);
                    }else if(actionObj.type=="attack3"){
                        this.showAttackName('反击',playerNode);
                    }

                    var result = _MFD.getDamage(player,target,false,null);

                    if(!result.isSuper){
                        this.behit(player,target,targetNode,result,'attack_pu',true,false);
                    }else{
                        this.behit(player,target,targetNode,result,'attack_bao',true,false);
                    }

                    this.node.runAction(
                        cc.sequence(
                            cc.delayTime((target.hp<=0?1.5:0.5)),
                            cc.callFunc(function(){
                                this.actionIndex++;
                                this.playerDoAction();
                            },this)
                        )
                    );
                }else{
                    this.actionIndex++;
                    this.playerDoAction();
                }
            }else if(actionObj.type=="skill"){

                var target = actionObj.target;
                var player = actionObj.player;
                var playerNode = this.getPlayerNodeByCode(player);
                var skill = actionObj.skill;
                var targetArr = actionObj.targetArr;
                var skillParam = actionObj.skillParam;

                if(
                    this.canUseSkill(player,skill)
                    &&_STATUSHELPERCHESS.canPlayerDoAction(player)
                ){
                    this.switchPlayerDirAndActtack(playerNode,target);
                    var runActions = _MCAC.getSkillAction(this,skill,target,targetArr,player,skillParam);
                    this.node.runAction(cc.sequence(runActions));
                }else{
                    this.actionIndex++;
                    this.playerDoAction();
                }

            }else if(actionObj.type=="item"){

                var target = actionObj.target;
                var player = actionObj.player;
                var playerNode = this.getPlayerNodeByCode(player);
                var item = actionObj.item;
                var targetArr = actionObj.targetArr;
                var itemParam = actionObj.itemParam;

                //消减道具数量
                _CU.cutArrNmb(window.gameData.fightItem,item)

                this.switchPlayerDirAndActtack(playerNode,target);
                var runActions = _MCAC.getItemAction(this,item,target,targetArr,player,itemParam);
                this.node.runAction(cc.sequence(runActions));

            }

        }else{

            if(!_MCRD.getRewardArr()){
                this.doActionEnd();
            }

        }

    },

    //判断并消耗技能蓝量
    canUseSkill:function(player,skill){

        var skillConf = _SKILL[skill];

        if(skillConf){
            var skillCut = skillConf.cut;
            if(player.hp>0&&player.mg>=skillCut){

                player.mg-=skillCut;

                return true;
            }
        }

        return false;

    },

    //结算奖励弹出
    doGetReward:function(rewardArr){

        //console.log('结算:',rewardArr);

        for(var i=0;i<rewardArr.length;i++){

            var tempPlayer = rewardArr[i].player;
            var rewards = rewardArr[i].arr;
            var playerNode = this.getPlayerNodeByCode(tempPlayer);
            //console.log('结算:',tempPlayer,playerNode);
            var rewardMsg = [];
            var shareArr = {};

            for(var j=0;j<rewards.length;j++){
                if(rewards[j].player&&rewards[j].player.code!=tempPlayer.code){//排查非本人奖励
                    if(!shareArr[rewards[j].player.code]){
                        shareArr[rewards[j].player.code]={
                                                            pnode:this.getPlayerNodeByCode(rewards[j].player),
                                                            msg:[]
                                                        }
                    }
                    shareArr[rewards[j].player.code].msg.push({msg:rewards[j].msg});
                }else{
                    rewardMsg.push({msg:rewards[j].msg});
                }
            }


            this.showTips(rewardMsg,playerNode);

            //共享经验&修为提示
            //console.log('结算',shareArr);
            for(var key in shareArr){
                this.showTips(shareArr[key].msg,shareArr[key].pnode);
            }

        }

        this.node.runAction(
            cc.sequence(
                cc.delayTime((1)),
                cc.callFunc(function(){
                    this.doActionEnd();
                },this)
            )
        );

    },

    //结算升级
    doLevelUp:function(levelUpPlayer){

        if(levelUpPlayer&&levelUpPlayer.length>0){

            for(var i=0;i<levelUpPlayer.length;i++){
                var tempPlayer = levelUpPlayer[i];
                var playerNode = this.getPlayerNodeByCode(tempPlayer);
                var playerData = _ROLEDATA.getRoleDataOfPlayer(tempPlayer);
                tempPlayer.hp = playerData.maxHp;
                tempPlayer.mg = playerData.maxMagic;
                _MFN.refreshPlayerNode(playerNode,tempPlayer);
                this.showTips([{msg:"升级"}],playerNode);
            }

        }

        this.doActionEnd();

    },

    //行动结束时结算
    doActionEnd:function(){

        
        if(this.currentPlayer.hp>0){

            this.refreshPlayerNodeMap();

            if(!this.canMoveAgain()){

                this.isfightOver();

            }

        }else{

            var tempRoleNode = this.getPlayerNodeByCode(this.currentPlayer);

            tempRoleNode.getChildByName('role').getComponent(cc.Animation).play('weak');

            this.node.runAction(
                cc.sequence(
                    cc.delayTime((1.5)),
                    cc.callFunc(function(){
                        
                        this.refreshPlayerNodeMap();

                        this.isfightOver();

                    },this)
                )
            );

        }
        


    },

    //是否可以再次移动
    canMoveAgain:function(){

        if(!_STATUSHELPERCHESS.canPlayerDoAction(_CHESSFIGHT.currentPlayer)){
            return;
        }

        var moveAgain = _ROLEDATA.getRealAttr(this.currentPlayer,'againMove');

        if(moveAgain>0){

            this.showCurrent("再移动");

            var mapPos = this.getPlayerPos(this.currentPlayer);
            this.currentFanwei =_MCFW.getfanweiMap(
                                            {
                                                x:mapPos.x,y:mapPos.y,
                                                len:moveAgain,
                                                attacklen:0,
                                                tiledMap:this.tiledMap,
                                                maxH:this.maxH,
                                                maxW:this.maxW,
                                                playerNodeMap:this.playerNodeMap,
                                                player:this.currentPlayer
                                            }
                                        );
            this.showfanweibyMap(this.currentFanwei);

            if(
                this.currentPlayer.isplayer
                &&!this.autofight
            ){//可操作角色显示移动界面
                this.currentCommond=null;
                this.canClick = true;
                this.onlyMove = true;
                return true;
            }else{//不可操作角色取离所有敌方单位最远的地点移动

                if(this.moveAgainToTarget()){
                    return true;
                }
                
            }

        }

        return false;

    },

    //再移动待机
    moveAndWait:function(x,y){

        this.targetX = x;
        this.targetY = y;
        this.waitAction();

    },

    //判断是否可以再移动
    moveAgainToTarget:function(){

        var moveTarget = _MCFW.getTargetForMoveAgain(this.currentFanwei,this.playerNodeMap,this.currentPlayer);
        if(moveTarget){
            this.moveAndWait(moveTarget.x,moveTarget.y);
            return true;
        }

        return false;
    },

    //行动前根据目标方位改变角色朝向
    switchPlayerDirAndActtack:function(playerNode,target){

        var playerRole = playerNode.getChildByName('role');
        playerRole.getComponent(cc.Animation).play('attack');
        if(target){
            this.switchPlayerDir(playerNode,[target.x,target.y]);
        }

    },

    //根据目标切换单位朝向 targetPosition [x,y]
    switchPlayerDir:function(currentPlayerNode,targetPosition){

        var currentPostion = currentPlayerNode.getPosition();
        var currentMapPos = _MANAGERMAP.getMapPos(currentPostion.x,currentPostion.y,this.maxH,this.maxW);

        if(targetPosition[0]<currentMapPos.x){
            currentPlayerNode.getChildByName('role').setScale(1,1);
        }else if(targetPosition[0]>currentMapPos.x){
            currentPlayerNode.getChildByName('role').setScale(-1,1);
        }

    },

    //调查角色
    checkRole:function(mapnode,event){

        var touchWorldPos=mapnode.convertToNodeSpaceAR(event.getLocation());
        var mapPos = _MANAGERMAP.getMapPos(touchWorldPos.x,touchWorldPos.y,_CHESSFIGHT.maxH,_CHESSFIGHT.maxW);
        var posKey = mapPos.x+"-"+mapPos.y;
        var roleinfo = this.playerNodeMap[posKey];

        if(roleinfo){

            console.log('调查',roleinfo);

            _MRDL.initUi(this.node,{sence:_STYPE._FIGHTSENCE,
                roleArr:this.getTeamByRole(roleinfo.info),
                roleIndex:0,
                scal:0.8
                });
        }
    },

    //调查数组
    getTeamByRole:function(player){

        var arr = [player];

        for(var key in this.playerNodeMap){

            if(
                this.playerNodeMap[key].info.code!=player.code
                &&this.playerNodeMap[key].info.isplayer==player.isplayer
            ){

                arr.push(this.playerNodeMap[key].info);

            }

        }

        return arr;
    },

    //地图点击事件
    mapClickFuc:function(event){

        if(_CHESSFIGHT.isCheck){
            _CHESSFIGHT.checkRole(this,event);
            _CHESSFIGHT.isCheck = false;
            _CHESSFIGHT.menuLabel.active = true;
            return ;
        }

        if(!_CHESSFIGHT.canClick){
            return;
        }

        var touchWorldPos=this.convertToNodeSpaceAR(event.getLocation());
        var mapPos = _MANAGERMAP.getMapPos(touchWorldPos.x,touchWorldPos.y,_CHESSFIGHT.maxH,_CHESSFIGHT.maxW);
        var posX = mapPos.x;
        var posY = mapPos.y;
        var posKey = posX+"-"+posY;
       
        if(!_CHESSFIGHT.currentCommond){//无命令 选择移动坐标阶段
            if(!_CHESSFIGHT.onlyMove){    
                _CHESSFIGHT.showAfterMove(posX,posY);
            }else{//再移动直接待机
                _CHESSFIGHT.moveAndWait(posX,posY);
            }
        }else if(_CHESSFIGHT.currentCommond==_MCF._ATYPE_ATTACK){
            if(_CHESSFIGHT.currentAttackFanwei
                &&_CHESSFIGHT.currentAttackFanwei[posKey]
                &&_CHESSFIGHT.currentAttackFanwei[posKey].isattack
            ){
                if(
                    !_CHESSFIGHT.playerNodeMap[posKey]
                    ||_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.playerNodeMap[posKey].info,"yin")
                ){
                    _TIPS.showMessage('没有可以攻击的目标');
                }else if(_CHESSFIGHT.playerNodeMap[posKey].info.isplayer==_CHESSFIGHT.currentPlayer.isplayer){
                    _TIPS.showMessage('不能攻击友军');
                }else{
                    //_TIPS.showMessage('可以攻击');
                    _CHESSFIGHT.attackAction(_CHESSFIGHT.playerNodeMap[posKey]);
                }
            }else{
                //_TIPS.showMessage('超出攻击范围');
                _CHESSFIGHT.cancelCommond();
            }
        }else if(_CHESSFIGHT.currentCommond==_MCF._ATYPE_SKILL){

            console.log('技能:',_CHESSFIGHT.currentSkill);
            console.log('坐标:',posX,posY);

            var skillConf = _SKILL[_CHESSFIGHT.currentSkill];
            var skillparam = null;

            //判断传送自身技能
            if(skillConf.skilltype=="move"){

                if(
                    _CHESSFIGHT.playerNodeMap[posKey]
                    ||!_CHESSFIGHT.currentAttackFanwei[posKey]
                ){
                    _TIPS.showMessage('必须为此技能选择一个范围内的空格子作为目标')
                    _CHESSFIGHT.cancelCommond();
                    return;
                }else{
                    skillparam = {x:posX,y:posY};
                }

            }else{

                if(
                    !_CHESSFIGHT.playerNodeMap[posKey]
                    ||_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.playerNodeMap[posKey].info,"yin")
                ){
                    _TIPS.showMessage('必须为此技能选择一个单位作为目标')
                    _CHESSFIGHT.cancelCommond();
                    return;
                }else if(
                    skillConf.target=="friend"
                    &&_CHESSFIGHT.playerNodeMap[posKey].info.isplayer!=_CHESSFIGHT.currentPlayer.isplayer
                ){
                    _TIPS.showMessage('必须为此技能选择一个友方单位作为目标')
                    _CHESSFIGHT.cancelCommond();
                    return;
                }else if(skillConf.target=="army"
                &&_CHESSFIGHT.playerNodeMap[posKey].info.isplayer==_CHESSFIGHT.currentPlayer.isplayer){
                    _TIPS.showMessage('必须为此技能选择一个敌方单位作为目标')
                    _CHESSFIGHT.cancelCommond();
                    return;
                }

                if(skillConf.skilltype=="moveAttack"){
                    var enablePosArr = _MCFW.getPosOfTargetForJump(posX,posY);
                    if(!enablePosArr||enablePosArr.length<=0){
                        _TIPS.showMessage('没有空余位置可以进行攻击');
                        _CHESSFIGHT.cancelCommond();
                        return;
                    }else{
                        skillparam = {enablePosArr:enablePosArr,targetPlayer:_CHESSFIGHT.playerNodeMap[posKey]};
                    }
                }else if(skillConf.skilltype=="moveRole"){
                    enablePosArr = _MCFW.getPosOfTargetForJump(_CHESSFIGHT.targetX,_CHESSFIGHT.targetY);
                    if(!enablePosArr||enablePosArr.length<=0){
                        _TIPS.showMessage('没有空余位置可以放置此人');
                        _CHESSFIGHT.cancelCommond();
                        return;
                    }else{
                        skillparam = {enablePosArr:enablePosArr,targetPlayer:_CHESSFIGHT.playerNodeMap[posKey]};
                    }
                }else if(!_CHESSFIGHT.currentAttackFanwei[posKey]){
                    _TIPS.showMessage('超出范围');
                    _CHESSFIGHT.cancelCommond();
                    return;
                }

            }

            _CHESSFIGHT.skillAction(_CHESSFIGHT.playerNodeMap[posKey],_CHESSFIGHT.currentSkill,skillparam);

        }else if(_CHESSFIGHT.currentCommond==_MCF._ATYPE_ITEM){

            var itemConf = _FIGHTITEM[_CHESSFIGHT.currentItem];
            if(
                !_CHESSFIGHT.playerNodeMap[posKey]
                ||_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.playerNodeMap[posKey].info,"yin")
            ){
                _TIPS.showMessage('必须为此技能选择一个单位作为目标')
                _CHESSFIGHT.cancelCommond();
                return;
            }else if(!_CHESSFIGHT.currentAttackFanwei[posKey]){
                _TIPS.showMessage('超出范围');
                _CHESSFIGHT.cancelCommond();
                return;
            }else if(
                itemConf.target=="friend"
                &&_CHESSFIGHT.playerNodeMap[posKey].info.isplayer!=_CHESSFIGHT.currentPlayer.isplayer
            ){
                _TIPS.showMessage('必须为此技能选择一个友方单位作为目标')
                _CHESSFIGHT.cancelCommond();
                return;
            }else if(itemConf.target=="army"
            &&_CHESSFIGHT.playerNodeMap[posKey].info.isplayer==_CHESSFIGHT.currentPlayer.isplayer){
                _TIPS.showMessage('必须为此技能选择一个敌方单位作为目标')
                _CHESSFIGHT.cancelCommond();
                return;
            }

            _CHESSFIGHT.itemAction(_CHESSFIGHT.playerNodeMap[posKey],_CHESSFIGHT.currentItem,null);
        }

    },

    highNodeByXY:function(x,y,fanweiinfo){

        var isattack = fanweiinfo.isattack;
        var ispass = fanweiinfo.ispass;
        var isbianjie = fanweiinfo.isbianjie;
        var nodearr = this.moveLabel.getChildren();
        x-=this.startX;
        y-=this.startY;
        if(
            nodearr[x]
            &&nodearr[x].getChildren()[y]
        ){
            if(isattack){
                nodearr[x].getChildren()[y].getChildByName('攻击').active = true;
            //}else if(isbianjie){
            }else{
                nodearr[x].getChildren()[y].getChildByName('行动').active = true;
            }
        }
    },

    hidefanwei:function(){

        var nodearr = this.moveLabel.getChildren();
        for(var i=0;i<nodearr.length;i++){
            for(var j=0;j<nodearr[i].getChildren().length;j++){
                nodearr[i].getChildren()[j].getChildren()[0].active = false;
                nodearr[i].getChildren()[j].getChildren()[1].active = false;
            }
        }

    },

    showfanweibyMap:function(map){

        var fanwearr = this.getfanweiByMap(map);

        for(var i=0;i<fanwearr.length;i++){
            var pos = fanwearr[i].pos;
            var x = pos[1];
            var y = pos[0];
            this.highNodeByXY(x,y,fanwearr[i]);
        }

    },

    showfanweibyPlayer:function(tmpplayer){

        this.hidefanwei();
        var tmpplayerData = _ROLEDATA.getRoleDataOfPlayer(tmpplayer);
        var tmpfanwei =_MCFW.getfanweiMap(
            {
                x:tmpplayer.chessPos.x,
                y:tmpplayer.chessPos.y,
                len:tmpplayerData.move,
                attacklen:tmpplayerData.distance,
                tiledMap:this.tiledMap,
                maxH:this.maxH,
                maxW:this.maxW,
                playerNodeMap:this.playerNodeMap,
                player:tmpplayer
            }
        );
        this.showfanweibyMap(tmpfanwei);

    },

    getfanweiByMap:function(result){
        var resultarr = [];
        for(var key in result){
            resultarr.push(result[key]);
        }
        return resultarr;
    },

    showAfterMove:function(x,y){

        if(!this.currentPlayer
            ||!this.currentRoleData){
            return false;
        }

        var tmpkey = x+"-"+y;

        if(
            this.currentFanwei
            &&this.currentFanwei[tmpkey]
        ){//点击在当前角色范围内的格子可执行：移动后操作 或者 直接攻击
            if(
                !this.currentFanwei[tmpkey].isattack
                &&!this.currentFanwei[tmpkey].ispass
            ){//选择可移动目标展示移动后操作
                this.hidefanwei();
                this.targetX=x;
                this.targetY=y;
                this.pointNode.active = true;
                this.pointNode.setScale(-this.currentPlayerNode.scaleX,this.currentPlayerNode.scaleY);
                var aniObj = _GRM.getAttackFrame(this.currentPlayer.pf);
                var aniArr = aniObj.walk;
                this.pointNode.getComponent(cc.Sprite).spriteFrame = aniArr[0];
                var npcmappos = _MANAGERMAP.getMapNodePosByTiled(x,y,this.maxH,this.maxW);
                this.pointNode.setPosition(npcmappos);
                this.fightSelectLabel.active = true;
                //this.fightSelectLabel.setPosition(this.pointNode.getPosition());
                return true;
            }else if(
                this.currentFanwei[tmpkey].isattack
                &&this.playerNodeMap[tmpkey]
                &&this.playerNodeMap[tmpkey].info.isplayer!=this.currentPlayer.isplayer
                &&!_STATUSHELPERCHESS.hasStatus(_CHESSFIGHT.playerNodeMap[tmpkey].info,"yin")
            ){//选中可攻击目标 直接攻击
                return this.attackTargetAction(this.playerNodeMap[tmpkey].info);
            }
        }

        return false;
    },

    //返回是否包含威风
    initOneFighter:function(team,i,flag,pointObj){

        var mappos = _MANAGERMAP.getMapObjPos(pointObj);
        var player = team[i];
        if(player){
            var playerData = _ROLEDATA.getRoleDataOfPlayer(player);
            var eg = playerData.beginEnergy;
            //var eg = _ROLEDATA.getRealAttr(player,'beginEnergy');
            this.initOneFighterReal(player,mappos,flag,eg,playerData.beginMagic);
            return playerData.weifeng>0;
        }

        return false;
    },

    initOneFighterReal:function(player,mappos,flag,eg,mg){
        player.mg = mg;
        player.eg = eg;
        player.code = this.getNextPlayerCode();
        var playerData = _ROLEDATA.getRoleDataOfPlayer(player);
        player.maxhpForShow = playerData.maxHp;

        var npcmappos = _MANAGERMAP.getMapNodePosByTiled(mappos.x,mappos.y,this.maxH,this.maxW);
        var fnode = _MFN.createPlayerNode(player,flag);
        fnode.setPosition(cc.v2(npcmappos));
        
        
        this.playerLabel.addChild(fnode);
        this.playerNodeMap[mappos.x+"-"+mappos.y]={node:fnode,info:player};
        this.setPlayerPos(player,mappos.x,mappos.y);
        
        this.setPlayerNodeByCode(player.code,player,fnode);

        if(
            playerData.beActive
            &&_MFD.canBianshen(player,false)
        ){
            this.showAttackName("激活",fnode);
        }

        return fnode;
    },

    //倒计时出生援军
    createExtraByTime:function(){

        for(var key in this.extraMap){

            if(this.playerNodeMap[this.extraMap[key].x+"-"+this.extraMap[key].y]){

                 console.log('没有空位出生援军不倒计时');
                 return;

            }else{

                this.extraMap[key].nmb--;

                if(this.extraMap[key].nmb<=0){

                    this.addExtraFighter(null,false,this.extraMap[key]);

                    this.extraMap[key].nmb = 5;
                }

                this.extraMap[key].node
                .getChildByName('xue')
                .getChildByName('putong').getComponent(cc.Label).string = this.extraMap[key].nmb;
            }
        }

    },

    //援军出生点
    initExtra:function(){

        if(this.tiledMap.getObjectGroup("extraPoint")
        &&this.tiledMap.getObjectGroup("extraPoint").getObjects()
        &&this.tiledMap.getObjectGroup("extraPoint").getObjects().length>0){

            var playerPoints = this.tiledMap.getObjectGroup("extraPoint").getObjects();

            for(var i=0;i<playerPoints.length;i++){
                
                var mappos = _MANAGERMAP.getMapObjPos(playerPoints[i]);

                var uiObj = _GRM.getNodeObj('armyFactory');

                this.playerLabel.addChild(uiObj.node);

                this.extraMap[mappos.x+"-"+mappos.y] = {x:mappos.x,y:mappos.y,nmb:5,node:uiObj.node};

                var npcmappos = _MANAGERMAP.getMapNodePosByTiled(mappos.x,mappos.y,this.maxH,this.maxW);

                uiObj.node.setPosition(npcmappos);

                uiObj.node.getChildByName('xue').getChildByName('putong').getComponent(cc.Label).string = 5;

            }

        }
    },

    //下一层传送
    initJump:function(){
        if(this.tiledMap.getObjectGroup("jump")
        &&this.tiledMap.getObjectGroup("jump").getObjects()
        &&this.tiledMap.getObjectGroup("jump").getObjects().length>0){

            var playerPoints = this.tiledMap.getObjectGroup("jump").getObjects();

            for(var i=0;i<playerPoints.length;i++){
                
                var mappos = _MANAGERMAP.getMapObjPos(playerPoints[i]);

                this.jumpMap[mappos.x+"-"+mappos.y] = 1;

            }

        }


    },

    //通关传送
    initPass:function(){
        if(this.tiledMap.getObjectGroup("pass")
        &&this.tiledMap.getObjectGroup("pass").getObjects()
        &&this.tiledMap.getObjectGroup("pass").getObjects().length>0){

            var playerPoints = this.tiledMap.getObjectGroup("pass").getObjects();

            for(var i=0;i<playerPoints.length;i++){
                
                var mappos = _MANAGERMAP.getMapObjPos(playerPoints[i]);

                this.passMap[mappos.x+"-"+mappos.y] = 1;

                this.hasPassPoint = true;
            }

        }


    },

    //援军
    addExtraFighter:function(type,isplayer,mappos){

        if(mappos
           &&this.playerNodeMap[mappos.x+"-"+mappos.y] 
        ){
            console.log('没有空位出生援军');
            return;
        }

        if(!isplayer){

            //计算锻造数
            if(!window.fightData.isFinal){
                var mapconf = _CMAP[window.fightData.chapter];
                var armyLiupai = mapconf.liupai;
                var dzlevel = mapconf.elevel+Math.floor(window.fightData.level);
                var armyLv = mapconf.level+window.fightData.level;
                if(armyLv>1000){
                    armyLv=1000;
                }
                var chapterLv = window.fightData.level>_CS.maxxw?999:window.fightData.level;
                var randomJob = _CU.randomObj(mapconf.army);
                var jobPath = null;
                if(armyLiupai&&armyLiupai[randomJob]){
                    jobPath=armyLiupai[randomJob];
                }
                //var player = _ROF.createRole(_CU.randomObj(mapconf.army));
                var player = _CROF.createJobRole(randomJob,
                                                {dzlevel:dzlevel,lv:armyLv,chapterLv:chapterLv,jobPath:jobPath}
                            );
                player.isboss = false;
                this.initOneFighterReal(player,mappos,false,100,0);
            }else{
                var mapconf = _FBOSS[window.fightData.chapter];
                var bossArr = mapconf.boss;
                var armyLv = mapconf.level;
                var dzlevel = mapconf.elevel;
                var chapterLv = mapconf.chapterLv;
                var chapter = mapconf.chapter;
                this.defaultMap = mapconf.map;

                var randomBoss = _CU.randomObj(bossArr);
                var player =    _CROF.createNpcRole(randomBoss,
                                    {dzlevel:dzlevel,lv:armyLv,chapterLv:chapterLv,chapter:chapter}
                                )
                player.isboss = true;
                this.initOneFighterReal(player,mappos,false,100,0);
            }
            //this.playSkill('biansen',mappos.x,mappos.y);
        }
    },

    //初始化对战节点
    initFighter:function(){

        var tmpcode = 0;

        var hasweifeng = false;

        if(this.tiledMap.getObjectGroup("playerPoint")
            &&this.tiledMap.getObjectGroup("playerPoint").getObjects()
            &&this.tiledMap.getObjectGroup("playerPoint").getObjects().length>0){

            var playerPoints = this.tiledMap.getObjectGroup("playerPoint").getObjects();

            for(var i=0;i<playerPoints.length;i++){

                tmpcode = (playerPoints[i].name/1-1);
                
                if(this.initOneFighter(window.fightData.playerTeam,tmpcode,true,playerPoints[i])){
                    hasweifeng = true;
                }

            }

        }

        if(this.tiledMap.getObjectGroup("armyPoint")
            &&this.tiledMap.getObjectGroup("armyPoint").getObjects()
            &&this.tiledMap.getObjectGroup("armyPoint").getObjects().length>0){

            var armyPoints = this.tiledMap.getObjectGroup("armyPoint").getObjects();

            for(var i=0;i<armyPoints.length;i++){

                tmpcode = (armyPoints[i].name/1-1);

                if(this.initOneFighter(window.fightData.armyTeam,tmpcode,false,armyPoints[i])){
                    hasweifeng = true;
                }
                
            }

        }

        //威风清零能量
        if(hasweifeng){
            for(var key in this.playerNodeMap){
                var tempplayerData = _ROLEDATA.getRoleDataOfPlayer(this.playerNodeMap[key].info);
                if(!tempplayerData.strongEnergy)
                    this.playerNodeMap[key].info.eg = 0;
            }
        }
    },

    initTitle:function(){

        var playerTitle = "我方武将";
        var playerFace = "问号";
        var armyFace = "问号";

        if(
            window.fightData
            &&window.fightData.playerTeam
            &&window.fightData.playerTeam.length>0
        ){
            playerTitle = window.fightData.playerTeam[0].name;
            playerFace = window.fightData.playerTeam[0].face;
        }

        if(
            window.fightData
            &&window.fightData.armyTeam
            &&window.fightData.armyTeam.length>0
        ){
            armyFace = window.fightData.armyTeam[0].face;
        }

        if(playerTitle){
            this.node.getChildByName('titleLabel')
            .getChildByName('zuo')
            .getChildByName('teamname')
            .getComponent(cc.Label)
            .string = playerTitle;
        }

        if(armyFace){
            this.node.getChildByName('titleLabel')
            .getChildByName('you')
            .getChildByName('gen')
            .getChildByName('img_touxian')
            .getChildByName('face')
            .getChildByName('img')
            .getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(armyFace);
        }

        if(playerFace){
            this.node.getChildByName('titleLabel')
            .getChildByName('zuo')
            .getChildByName('gen')
            .getChildByName('img_touxian')
            .getChildByName('face')
            .getChildByName('img')
            .getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(playerFace);
        }

        if(this.isTaskModel()
            &&window.gameData.workList
            &&window.gameData.workList.length>0
        ){
            this.node.getChildByName('titleLabel')
                .getChildByName('you')
                .getChildByName('teamname')
                .getComponent(cc.Label)
                .string = window.gameData.workList[0].taskname;
        }else{
            if(window.fightData.chapter){
                this.node.getChildByName('titleLabel')
                .getChildByName('you')
                .getChildByName('teamname')
                .getComponent(cc.Label)
                .string = window.fightData.chapter;
            }else{
                this.node.getChildByName('titleLabel')
                .getChildByName('you')
                .getChildByName('teamname')
                .getComponent(cc.Label)
                .string = window.fightData.boss?window.fightData.boss:"???";
            }
        }

    },

    refreshStepNmb:function(){
        if(this.isTaskModel()){
            this.node.getChildByName('titleLabel').getChildByName('zuo')
                    .getChildByName('gen').getChildByName('steplabel')
                    .getComponent(cc.Label).string=this.playerStep+"/"+_CS.stepMax;
        }else{
            this.node.getChildByName('titleLabel').getChildByName('zuo')
            .getChildByName('gen').getChildByName('steplabel')
            .getComponent(cc.Label).string=this.playerStep;
        }
        this.node.getChildByName('titleLabel').getChildByName('you')
                    .getChildByName('gen').getChildByName('steplabel').getComponent(cc.Label).string=this.armyStep;
    },

    refreshTitle:function(){

        this.refreshTotalBlood(window.fightData.playerTeam,this.node.getChildByName('titleLabel').getChildByName('zuo'));
        this.refreshTotalBlood(window.fightData.armyTeam,this.node.getChildByName('titleLabel').getChildByName('you'));
        this.refreshOrder(this.node.getChildByName('titleLabel'));
    },

    refreshOrder:function(node){

        var orderArr = this.getNextOrder();
        var faceNodeArr = node.getChildByName('su').getChildren();
        for(var i=faceNodeArr.length-1;i>=0;i--){
            var facenode = faceNodeArr[i];
            if(orderArr[i]){
                var info = orderArr[i];
                facenode.active = true;

                facenode.getChildByName('label').getComponent(cc.Label).string = info.name;
                facenode.getChildByName('New Node')
                .getChildByName('官弓').getComponent(cc.Sprite).spriteFrame = _GRM.getFaceFrame(info.face);
                facenode.getChildByName('mask_touxiang').color = new cc.color(info.isplayer?_CS.bloodColor['player']:_CS.bloodColor['army']);

            }else{
                facenode.active = false;
            }

        }

    },

    refreshTotalBlood:function(team,node){
        var total = 0;
        var current = 0;
        for(var i=0;i<team.length;i++){
            total+=team[i].maxhpForShow;
            current+=team[i].hp;
        }

        node.getChildByName('bloodlabel').getComponent(cc.Label).string=_CU.getUnitNmb(current)+" / "+_CU.getUnitNmb(total);
        node.getChildByName('gen').getChildByName('blood').getComponent(cc.ProgressBar).progress = current/total;
    },

    getNextOrder:function(){

        var nextArr = [];
        var tmpinfoArr = [];
        var nospeed = true;

        for(var key in this.playerNodeMap){

            var tmpinfo = this.playerNodeMap[key].info;
            var tmpeg = tmpinfo.eg;
            var face = tmpinfo.face;
            var code = tmpinfo.code;
            var name = tmpinfo.name;
            var isplayer = tmpinfo.isplayer;
            var speed = _ROLEDATA.getRealAttr(tmpinfo,'speed');
            
            tmpinfoArr.push({name:name,eg:tmpeg,face:face,code:code,isplayer:isplayer,speed:speed});

            if(speed>0){
                nospeed = false;
            }
        }

        while(nextArr.length<8&&!nospeed){


            tmpinfoArr.sort((a,b)=>{
                return b.eg-a.eg;
            });

            if(tmpinfoArr[0].eg>=100){

                tmpinfoArr[0].eg-=100;

                nextArr.push(_CU.cloneObj(tmpinfoArr[0]));

            }else{

                for(var i=0;i<tmpinfoArr.length;i++){
                    tmpinfoArr[i].eg+=tmpinfoArr[i].speed;
                }

            }

        }

        return nextArr.reverse();

    },

    //获取协战角色列表
    getXiezhanArr:function(player,target){

        var arr = [];

        for(var key in this.playerNodeMap){
            var xiezhanplayer = this.playerNodeMap[key].info;
            if(
                xiezhanplayer.isplayer == player.isplayer
                &&xiezhanplayer.code != player.code
                &&_ROLEDATA.getRealAttr(xiezhanplayer,'xiezhan')
            ){
                var distance = _ROLEDATA.getRealAttr(xiezhanplayer,'distance');
                var armydistance = _CU.getPlayerDis(xiezhanplayer,target);
                if(distance>=armydistance){
                    arr.push(xiezhanplayer);
                }
            }

        }

        return arr;
    },

    //伤害字体
    showDamage:function(msg,msgcolor,playerNode){
       this.showTips([{msg:_CU.getUnitNmb(msg),color:msgcolor}],playerNode);
    },

    //文字提示
    showAttackName:function(msg,playerNode){
        this.showTips([{msg:msg,color:_CS.skillcolor}],playerNode);
    },

    //文字提示当前角色
    showCurrent:function(msg){
        if(this.currentPlayerNode)
        this.showAttackName(msg,this.currentPlayerNode);
    },

    showTips:function(messageArr,tnode){

        var nodeArr = this.node.getChildByName('tips').getChildren();

        for(var i=0;i<messageArr.length;i++){
            var node = nodeArr[this.tipsIndex];
            node.getComponent(cc.Label).string = "";
            node.stopAllActions();
            if(!tnode){
                node.setPosition(0,0);
            }else{
                node.setPosition(tnode.getPosition());
            }
            node.msgObj = messageArr[i];
            node.runAction(
                cc.sequence(
                    cc.delayTime(i*0.2),
                    cc.callFunc(function(){
                        this.getComponent(cc.Label).string = this.msgObj.msg;
                        if(this.msgObj.color){
                            this.color = new cc.color(this.msgObj.color);
                        }else{
                            this.color = new cc.color("FFFFFF");
                        }
                    },node),
                    cc.moveBy(0.5,0,30),
                    cc.delayTime(0.2),
                    cc.callFunc(function(){
                        this.getComponent(cc.Label).string = "";
                    },node)
                )
            );

            this.tipsIndex++;
            if(this.tipsIndex>=nodeArr.length){
                this.tipsIndex=0;
            }
        }

    },

    playSkillOnPlayer:function(skillName,player){
        this.playSkill(skillName,player.chessPos.x,player.chessPos.y);
    },

    playSkill:function(skillName,x,y){

        var nodeArr = this.skillaniLabel.getChildren();
        var tempNode = nodeArr[this.aniIndex];
        if(this.aniIndex<nodeArr.length-1){
            this.aniIndex++;
        }else{
            this.aniIndex=0;
        }

        var skillPos = _MANAGERMAP.getMapNodePosByTiled(x,y,this.maxH,this.maxW);
        tempNode.setPosition(skillPos);
        tempNode.stopAllActions();
        tempNode.active = true;
        var aniarr = _GRM.getSkillFrame(skillName);
        var delayTime = aniarr.length*0.1;
        if(aniarr){
            tempNode.getComponent(cc.Sprite).spriteFrame = aniarr[0];
            var clipu = _GRM.createAniClip(aniarr,skillName,cc.WrapMode.Normal);
            tempNode.getComponent(cc.Animation).addClip(clipu);
            tempNode.getComponent(cc.Animation).play(skillName);
        }else{
            tempNode.getComponent(cc.Sprite).spriteFrame = null;
        }

        tempNode.runAction(cc.sequence(
            cc.delayTime(delayTime),
            cc.callFunc(function(){
                this.active = false;
            },tempNode)
        ));
        
        return delayTime;
    },

    isTaskModel:function(){
        if(window.fightData.isTaskModel){
            return true;
        }else{
            return false;
        }
    }

    // update (dt) {},
});
